package com.wordsay.parser.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.wordsay.common.Constant;
import com.wordsay.entity.People;
import com.wordsay.entity.PersonDialog;
import com.wordsay.entity.Talk;
import com.wordsay.parser.ChatParser;
import com.wordsay.util.TalkUtil;


public class FxPersonChatParser implements ChatParser {

	private static Logger log = LogManager.getLogger(FxPersonChatParser.class.getName());

	//fx talk start pattern : .*\s\([0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}\)˵:
	
	@Override
	public Object parse(String chatFilePath) throws Exception {

		log.info("start parse chat file ["+chatFilePath+"] in FxPerson chat parser");

		File chatFile = new File(chatFilePath);
		
//		BufferedReader reader = new BufferedReader(new FileReader(chatFilePath));
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(chatFilePath),"utf-8"));

		PersonDialog dialog = new PersonDialog();
		
		String fileName = chatFile.getName();
		People otherPeople = new People();
		otherPeople.setId(TalkUtil.parseTalkId(fileName, Constant.PEOPLE_TALK));
		otherPeople.setName(fileName.substring(0,fileName.indexOf("(")));
		
		String line = null;
		while((line = reader.readLine()) != null) {
			
			if(TalkUtil.isFxNewTalk(line)){
			 
				Talk talk = TalkUtil.parseFxMessage(line);
				if(talk == null){
					continue;
				}
				dialog.getTalks().add(talk);
				
			} else {
			
				if(dialog.getLastTalk() == null){
					continue;
				}
				dialog.getLastTalk().appendMessage(line);
			}
			
		}
		
		dialog.setOtherPeople(otherPeople);
		return dialog;
	}

}
